package com.atguigu.lease.common.jwtutil;

import com.atguigu.lease.common.exception.BusException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;
//@SuppressWarnings("all")

public class JwtUtil {
    private static  final long TOKEN_TTL_TIME =  60 * 60 * 1000L;
    private static final SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());
    public static String createToken(Long userId, String userName) {
        String token = Jwts.
                builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + TOKEN_TTL_TIME)).
                claim("userId", userId).
                claim("username", userName).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }

    public static Claims parseToken(String token){
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(tokenSignKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new BusException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new BusException(ResultCodeEnum.TOKEN_INVALID);
        }
    }



}